package core;

import java.util.List;

import javax.swing.SwingWorker;

import db.Mapper;

public class LoginTask extends SwingWorker<Void, Integer>
{
	private ChatNode node;
	private String loginName;
	
	LoginTask(String name, ChatNode node)
	{
		this.node = node;
		this.loginName = name;
	}
	
	public String getLoginName()
	{
		return loginName;
	}

	@Override
	protected Void doInBackground()
	{
		setProgress(0);
		while(!isCancelled() && getProgress()<3)
		{
			try
			{
				Thread.sleep(1000);
				setProgress(getProgress() + 1);
				publish(getProgress());
			}
			catch(InterruptedException ex)
			{
				node.getServer().stop();
				node.setIp(null);
				node.setName(null);
				node.getMainWindow().setStopped();
			}
		}
		
		return null;
	}
	
	@Override
	protected void process(List<Integer> chunks)
	{
		for(Integer chunk : chunks)
		{
			node.getMainWindow().appendUser(String.valueOf(3-chunk));  
		}
		
	}
	
	@Override
	protected void done()
	{
		try
		{
			super.get();
			
			node.setName(loginName);
			
			Mapper userbase = node.getUserBase();
			String[] userList = userbase.getPeersArray();
			node.getMainWindow().setUserList(userList);
			node.getMainWindow().setLoggedIn();
			
			String myAddress = node.getIp() + ":" + node.getPort();
			
			RequestBroadcaster broadcaster = node.getRequestBroadcaster();
			broadcaster.broadcastSendName(node.getName(), myAddress, 1);
			
		}
		catch(Throwable t)
		{
			//TODO: report any failure that might have occurred
		}
	}
	
}
